package org.net5ijy.commons.http.test;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 进度条
 *
 * @author xuguofeng
 * @date 2020/9/15 9:56
 */
public class ProgressBar {

  /**
   * 进度条粒度
   */
  private static final int PROGRESS_SIZE = 100;

  private static ProgressBar progressBar = new ProgressBar();

  private ProgressBar() {

  }

  public static ProgressBar getProgressBar() {
    return progressBar;
  }

  private String getNChar(int num, char ch) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < num; i++) {
      builder.append(ch);
    }
    return builder.toString();
  }

  public void printProgress(int progress) {

    System.out.print(getNChar(PROGRESS_SIZE + 25, '\b'));
    System.out.print("Progress:");

    String finish = getNChar(progress, '#');
    String unFinish = getNChar(PROGRESS_SIZE - progress, '-');

    String target = String.format("%3d%% |%s%s|", progress, finish, unFinish);
    System.out.print(target);
  }

  public void printProgressWithoutPercentage() {
    System.out.print(getNChar(14, '\b'));
    System.out.print("Downloading...");
  }

  public static void main(String[] args) throws InterruptedException {

    Random random = new Random();

    ProgressBar progressBar = ProgressBar.getProgressBar();

    for (int i = 0; i <= PROGRESS_SIZE; i++) {
      progressBar.printProgress(i);
      TimeUnit.MILLISECONDS.sleep(random.nextInt(1000));
    }
  }
}
